package springboot.config;

import java.io.IOException;
import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

@Configuration
public class FreeMarkerConfig {
	  @Bean
	  public ViewResolver viewResolver() {
	    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
	    resolver.setViewClass(org.springframework.web.servlet.view.freemarker.FreeMarkerView.class);
	    resolver.setCache(false);
	    resolver.setSuffix(".ftl");
	    resolver.setExposeSpringMacroHelpers(true);
	    resolver.setExposeRequestAttributes(true);
	    resolver.setExposeSessionAttributes(true);
	    resolver.setRequestContextAttribute("request");
	    resolver.setContentType("text/html; charset=UTF-8");
	    return resolver;
	  }

	  @Bean
	  public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
	    FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
	    //
	    FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
	    factory.setTemplateLoaderPaths("classpath:/templates/", "src/main/webapp/WEB-INF/templates/");
	    factory.setDefaultEncoding("UTF-8");
	    freemarker.template.Configuration configuration = factory.createConfiguration();
	    configuration.setClassicCompatible(true);
	    configuration.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
	    configurer.setConfiguration(configuration);
	    //
	    Properties settings = new Properties();
	    settings.put("template_update_delay", "0");
	    settings.put("default_encoding", "UTF-8");
	    settings.put("number_format", "0.##");
	    settings.put("datetime_format", "yyyy-MM-dd HH:mm:ss");
	    //settings.put("classic_compatible", true);
	    //settings.put("template_exception_handler", "ignore");
	    configurer.setFreemarkerSettings(settings);
	    return configurer;
	  }
}
